<template>
  <div class="news-edit">
    <div class="header">
      <h2>编辑新闻</h2>
    </div>

    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="80px"
      class="news-form"
      v-loading="loading"
    >
      <el-form-item label="标题" prop="title">
        <el-input v-model="form.title" placeholder="请输入新闻标题" />
      </el-form-item>

      <el-form-item label="摘要" prop="summary">
        <el-input
          v-model="form.summary"
          type="textarea"
          :rows="2"
          placeholder="请输入新闻摘要"
        />
      </el-form-item>

      <el-form-item label="作者" prop="author">
        <el-input v-model="form.author" placeholder="请输入作者" />
      </el-form-item>

      <el-form-item label="封面图片" prop="image">
        <el-upload
          class="image-upload"
          action="/api/upload/image"
          :show-file-list="false"
          :on-success="handleImageSuccess"
          :before-upload="beforeImageUpload"
          :headers="{ Authorization: `Bearer ${userStore.token}` }"
        >
          <img v-if="form.image" :src="form.image" class="image-preview">
          <el-button v-else type="primary">上传封面图片</el-button>
        </el-upload>
      </el-form-item>

      <el-form-item label="内容" prop="content">
        <el-input
          v-model="form.content"
          type="textarea"
          :rows="6"
          placeholder="请输入新闻内容"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" :loading="submitting" @click="handleSubmit">
          保存
        </el-button>
        <el-button @click="handleCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'
import { getDetail, update } from '@/api/news'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()
const formRef = ref()
const loading = ref(false)
const submitting = ref(false)

const form = reactive({
  title: '',
  summary: '',
  content: '',
  author: '',
  image: ''
})

const rules = {
  title: [
    { required: true, message: '请输入新闻标题', trigger: 'blur' },
    { min: 2, max: 100, message: '标题长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  summary: [
    { required: true, message: '请输入新闻摘要', trigger: 'blur' },
    { max: 500, message: '摘要不能超过 500 个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入新闻内容', trigger: 'blur' }
  ],
  author: [
    { required: true, message: '请输入作者', trigger: 'blur' },
    { max: 50, message: '作者名不能超过 50 个字符', trigger: 'blur' }
  ]
}

const loadNews = async () => {
  const id = route.params.id
  if (!id) return

  loading.value = true
  try {
    const res = await getDetail(id)
    if (res.code === 200) {
      Object.assign(form, res.data)
    } else {
      ElMessage.error(res.message || '获取新闻详情失败')
    }
  } catch (error) {
    console.error('获取新闻详情失败:', error)
    ElMessage.error('获取新闻详情失败')
  } finally {
    loading.value = false
  }
}

const handleImageSuccess = (res) => {
  if (res.code === 200) {
    form.image = res.data
    ElMessage.success('图片上传成功')
  } else {
    ElMessage.error('图片上传失败')
  }
}

const beforeImageUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    submitting.value = true

    const res = await update(route.params.id, form)
    if (res.code === 200) {
      ElMessage.success('更新成功')
      router.push('/admin/news')
    } else {
      ElMessage.error(res.message || '更新失败')
    }
  } catch (error) {
    console.error('更新新闻失败:', error)
    ElMessage.error(error.message || '更新失败')
  } finally {
    submitting.value = false
  }
}

const handleCancel = () => {
  router.push('/admin/news')
}

onMounted(() => {
  loadNews()
})
</script>

<style lang="scss" scoped>
.news-edit {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  
  .header {
    margin-bottom: 20px;
    
    h2 {
      margin: 0;
      font-size: 20px;
      font-weight: 500;
      color: #000; /* 添加黑色 */
    }
  }
  
  .news-form {
    max-width: 800px;
    
    .el-button {
      margin-right: 10px;
    }
  }

  .image-upload {
    .image-preview {
      width: 200px;
      height: 200px;
      object-fit: cover;
      border-radius: 4px;
    }
  }
}
</style> 